﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using Zjh.PackSerializer.Attributes;

namespace Zjh.PackSerializer
{
    public class PackContract : Collection<PackMember>
    {
        public Type ContractType { get; }

        private PackContract(Type type)
        {
            ContractType = type;
            LoadMembers();
        }

        private void LoadMembers()
        {
            var items = new List<PackMember>();
            foreach (var prop in ContractType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                PackMember member = PackMember.TryCreateInstance(prop);
                if (member != null)
                {
                    items.Add(member);
                }
            }
            foreach (var member in items.OrderBy(m => m.Index))
            {
                this.Add(member);
            }
        }

        public static PackContract TryCreateInstance(Type type)
        {
            if (type.GetCustomAttribute(typeof(PackContractAttribute)) != null)
            {
                return new PackContract(type);
            }
            return null;
        }
    }
}